package com.gitee.huanminabc.dynamicdb.common;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author huanmin
 * @date 2024/11/22
 */
@Component("DbSpringContextHolder")
public class SpringContextHolder implements ApplicationContextAware {


    /**
     *       * 上下文对象实例
     *
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }

    /**
     * 获取Spring上下文
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }



    public static Object getBean(String name) {
        try {
            return getApplicationContext().getBean(name);
        } catch (Exception e) {
            throw new DynamicDbException(e);
        }
    }

    public static Object getBean(Class c) {
        try {
            return getApplicationContext().getBean(c);
        } catch (Exception e) {
            throw new DynamicDbException(e);
        }
    }
}